package araxy.blog.interceptor;

import araxy.blog.TotalStatus;
import araxy.blog.utils.RedisUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Base64;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
public class DatabaseInterceptor {

    @Pointcut("execution(* araxy.blog.service..*.get*(..))")
    private void getData() {}

    @Pointcut("execution(* araxy.blog.service..*.getArticleBytesById(..))")
    private void getArticleBytes() {}

    @Around("getArticleBytes()")
    public Object ArticleBytes(ProceedingJoinPoint joinPoint) throws Throwable {
        Object obj = null;
        String id = null;

        if (TotalStatus.isRedis()) {
            //到redis中查询，如果有数据直接返回
            Object[] args = joinPoint.getArgs();
            id = (String) args[0];
            id = "article" + "-" + id;
            try {
                obj = RedisUtil.getRedisTemplate().opsForValue().get(id);
                if (obj != null) {
                    return Base64.getDecoder().decode(obj.toString());
                }
            } catch (Exception ignored) {

            }
        }
        obj = joinPoint.proceed();
        if (TotalStatus.isRedis()) {
            //将获得的数据写入redis
            try {
                RedisUtil.getRedisTemplate().opsForValue().set(id,obj,6, TimeUnit.HOURS);
            } catch (Exception ignored) {

            }
        }
        return obj;
    }
}
